<?php
/**
 *
 *
 *
 */
namespace Yz\modules\Uploads;

class Model_Upload
    extends \Yz_Model_ActiveRecord
{
    // The name of upload controller is 'Upload' + this._name_
    // const UPLOAD_CONTROLLER = 'Upload';
    const UPLOAD_PATH   = 'www/%A/%M/%N/';

    protected $uploadPath;


    /** Model's fields definition
     */
    protected function init()
    {
        debug();
        $d =& $this->__dict__;
        $d['id']           = new \Yz_Model_Field_Id();
        $d['filename']     = new \Yz_Model_Field_String();
        $d['originalname'] = new \Yz_Model_Field_String();
        $d['extension']    = new \Yz_Model_Field_String();
        $d['created']      = new \Yz_Model_Field_Timestamp();
        $d['filesize']     = new \Yz_Model_Field_Number();
        return $this;
    }


    /**************************
     *      Public methods    *
     **************************/

    /**
     *
     *  @return Item
     *  @throw
     */
    public function processUpload($uploadName)
    {
        $action = $this
            ->selectAction('Upload')
            ->setUploadName($uploadName)
        ;
        return $this->_process($action);
    }


    /**
     *
     */
    public function getUploadController()
    {
        return 'Upload' . $this::_name_();
    }

    /**
     *
     */
    public function getUploadPath()
    {
        $uploadPath =& $this->uploadPath;
        if (null === $uploadPath) {
            $const = static::UPLOAD_PATH;
            $class = $this;
            while (false === $const) {
                $class = get_parent_class($class);
                $const = $class::UPLOAD_PATH;
            }
            $uploadPath = strtr($const,array(
                '%A' => \Yz::getName(), // application namespace
                '%M' => \Yz_String::fromCamelCase(lcfirst($this->module->getName())), // module name
                '%N' => \Yz_String::fromCamelCase(lcfirst($class::_name_())), // model name
            ));
        }

        return $uploadPath;
    }

    /*****************************
     *      Protected methods    *
     *****************************/

    protected function _process($action)
    {
        $uploadPath = $this->getUploadPath();
        $values = $action
            ->setUploadPath($uploadPath)
            ->perform()
        ;
        return $this->item()->newValues(); // use preset values
        //return $this->item()->assignValues($values);
    }

}
